import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { BladeData } from "../../../../shared/blade/blade-data";
import { Blade } from "../../../../shared/blade/blade.model";
import { Command } from "../../../../shared/toolbar.service";
import { ModelParamService } from "../../../../service/model-param.service";
import { ModelParam } from "../../../../entity/model-Param";
import { MyValidators } from "../../../../utils/validator/rang";
@Component({
  selector: 'app-model-param-edit',
  templateUrl: './model-param-edit.component.html',
  styleUrls: ['./model-param-edit.component.css']
})
export class ModelParamEditComponent extends BladeContainerBase<ModelParam> {

  constructor(
    private modelParamService: ModelParamService,
    private fb: FormBuilder,
  ) {
    super(fb);
  }

  ngOnInit() {
    if (!this.isNew) {
      this.commands = [
        new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new ModelParam(0, this.parentEntity[0] ? this.parentEntity[0].deviceCategoryId : 0, 0, "", "");

    }
    super.ngOnInit();
  }
  /**
      * 初始化数据
      * 
      * 
      * @memberof TagEditComponent
      */
  initData(): any | Observable<any> | Promise<any> {

    this.formPatchValue(this.currentEntity);


  }
  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }
  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    return this.hasChange();
  }
  createForm() {
    let obj: {} = {
      "modelParamName": [this.currentEntity.modelParamName, [
        Validators.required,
        Validators.maxLength(20),
      ], (control: FormControl): any => this.modelParamNameAsnyValidator(control)],
      "deviceCategoryId": [this.currentEntity.deviceCategoryId],
      "modelParamKey": [this.currentEntity.modelParamKey, [
        Validators.required,
        Validators.pattern("^[a-zA-Z]+$"),
        Validators.maxLength(20),
      ], (control: FormControl): any => this.modelParamKeyAsnyValidator(control)],
      "defaultParamValue": [this.currentEntity.defaultParamValue, [
        Validators.pattern("^[0-9]+(.[0-9]{0,2})?$"),
        Validators.maxLength(20),
      ]],
      "seq": [this.currentEntity.seq, [
        Validators.pattern("[0-9]*"),
        Validators.maxLength(10),
      ]],
      "unit": [this.currentEntity.unit]

    };
    this.formGroup = this.fromBuider.group(obj);
  }
  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      "modelParamName": "",
      "modelParamKey": "",
      "defaultParamValue": "",
    };
  }
  canCreate() {
    return !this.formGroup.value.deviceCategoryId || !this.formGroup.valid;
  }
  /**
  * 设置表单验证信息
  * 
  * 
  * @memberof BladeContainerBase
  */
  setValidationMessages(): void {
    this.validationMessages = {
      "modelParamName": {
        'required': '型号参数名称不能为空。',
        'maxlength': '型号参数名称不能多于20个字符长度。',
        "exist": "型号参数名称已存在"
      },
      "modelParamKey": {
        'required': '型号参数不能为空。',
        'pattern': '型号参数必须字母组成。',
        'maxlength': '型号参数不能多于20个字符长度。',
        "exist": "型号参数Key已存在"
      },
      "defaultParamValue": {
        'pattern': '默认值必须数字组成。',
        'maxlength': '默认值不能多于20个字符长度。',
      },



    };
  }
  modelParamNameAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.modelParamName) {
      return Observable.of(null);
    }
    return this.modelParamService.hasmodelParamName(control.value, this.currentEntity.deviceCategoryId)
      .map(res => res ? { exist: true } : null);
  }
  modelParamKeyAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.modelParamKey) {
      return Observable.of(null);
    }
    return this.modelParamService.hasmodelParamKey(control.value, this.currentEntity.deviceCategoryId)
      .map(res => res ? { exist: true } : null);
  }
  /**
   * 创建一个测点信息
   * 
   * 
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.modelParamService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          } else {
            throw new Error("数据新增失败！")
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }
  /**
   * 
   * 
   * 
   * @memberof TagsEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent()
      return this.modelParamService.update(this.currentEntity)
        .then(res => {

          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
          throw new Error("数据更新失败！")

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }
  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;
    this.currentEntity.modelParamName = formValue.modelParamName;
    this.currentEntity.defaultParamValue = formValue.defaultParamValue;
    this.currentEntity.modelParamKey = formValue.modelParamKey;
    this.currentEntity.unit = formValue.unit;
    this.currentEntity.seq = formValue.seq;
    this.currentEntity.deviceCategoryId = formValue.deviceCategoryId;
  }

}



// WEBPACK FOOTER //
// ./src/app/module/basic/model-param/model-param-edit/model-param-edit.component.ts